package zd.cornermemory.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;

import zd.cornermemory.R;
import zd.cornermemory.utils.Dictionary;
import zd.cornermemory.utils.FileUtil;
import zd.cornermemory.utils.PicassoUtil;
import zd.cornermemory.utils.SPUtils;
import zd.cornermemory.utils.Uri2PathUtil;
import zd.cornermemory.view.CustomDialog;

import static zd.cornermemory.utils.Utils.hideKeyboard;
import static zd.cornermemory.utils.Utils.showKeyboard;

public class LxPicActivity extends BaseActivity {
    private EditText  ans;
    private TextView  remark;
    private TextView  no_data;
    private TextView  reset;
    private ImageView img;
    private String ansStr;
    private Button query_button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lx_pic);
        ans = findViewById(R.id.ans);
        remark = findViewById(R.id.remark);
        reset = findViewById(R.id.reset);
        no_data = findViewById(R.id.no_data);
        img = findViewById(R.id.img);
        query_button = findViewById(R.id.query_button);
        ans.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                return search();
            }
        });
        ans.setTransformationMethod(new UpperCaseTransform());
        setBackImage();
        query_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search();
            }
        });
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestExternal();
            }
        });
        remark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!TextUtils.isEmpty(remark.getText().toString())){
                    update(remark,ans.getText().toString().trim().toUpperCase());
                }
            }
        });

        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(mContext)
                        .setTitle(ansStr + getString(R.string.pic_defult))
                        .setMessage(getString(R.string.sure_))
                        .setCancelable(false)
                        .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {

                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SPUtils.getInstance().remove(ansStr + "_LX");
                                SPUtils.getInstance().remove(ansStr + "_LXPIC");
                                search();
                            }
                        }).show();
            }
        });
    }

    private boolean search() {
        remark.setText("");
        ansStr = ans.getText().toString().trim().toUpperCase();
        String lxc = Dictionary.dic.get(ansStr);
        if (TextUtils.isEmpty(lxc)) {
            lxc = ansStr;
        }
        String lxStr = SPUtils.getInstance().getString(ansStr+"_LX",lxc);
        String lxPic = SPUtils.getInstance().getString(ansStr+"_LXPIC","");
        remark.setText(lxStr);
        if (!TextUtils.isEmpty(lxPic)) {
            PicassoUtil.showPicture(mContext,lxPic,img);
            reset.setVisibility(View.VISIBLE);
            return true;
        }

        if (TextUtils.isEmpty(lxPic)) {
            Integer a = Dictionary.pic.get(ansStr);
            if (a != null) {
                img.setVisibility(View.VISIBLE);
                img.setImageResource(a);
                no_data.setVisibility(View.GONE);
                reset.setVisibility(View.GONE);
            }else{
                img.setImageResource(R.drawable.image_error);
                reset.setVisibility(View.GONE);
            }
            return true;
        }
        return false;
    }

    private void requestExternal() {
        PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permissions) {
                openAlbum();
            }

            @Override
            public void permissionDenied(@NonNull String[] permissions) {
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    public static final int CHOOSE_PHOTO = 2;
    String imagePath = null;
    private void openAlbum(){
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO); //打开相册
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CHOOSE_PHOTO:
                if(resultCode == RESULT_OK){
                    //判断手机系统版本号
                    if(Build.VERSION.SDK_INT>=19){
                        //4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageOnKitKat(Intent data){
        Uri uri = data.getData();
        imagePath = Uri2PathUtil.getPath(this,uri);
        displayImage(imagePath); //根据图片路径显示图片
    }

    //展示图片
    private void displayImage(String imagePath){
        if(imagePath!=null && !imagePath.equals("")){
//            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//            img.setImageBitmap(bitmap);

            PicassoUtil.showPicture(mContext,imagePath,img);
            File fileImage = new File(imagePath);
            if(!FileUtil.checkFileSize(fileImage)){
                showProgressDialog(getString(R.string.hanle_),false);
                handleImage(fileImage);
            }else{
                SPUtils.getInstance().put(ansStr+"_LXPIC",imagePath);
            }
        }else {
            Toast.makeText(this,getString(R.string.get_pic_faile),Toast.LENGTH_SHORT).show();
        }
    }


    private View view;
    private EditText editText;
    private void update(final TextView e, final String title) {
        LayoutInflater factory = LayoutInflater.from(mContext);
        int layoutId = R.layout.edit_remark_layout;
        view = factory.inflate(layoutId, null);
        editText = (EditText) view.findViewById(R.id.edit_text);
        String s = e.getText().toString();
        editText.setText(s);
        editText.setSelection(s.length());
        new CustomDialog.Builder(mContext).setTitle(title).setView(view)
                .setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        hideKeyboard(editText);
                    }
                }).setNegativeButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String str = editText.getText().toString().trim();
                if(!TextUtils.isEmpty(str)){
                    e.setText(str);
                    SPUtils.getInstance().put(title+"_LX",str);
                }
            }
        }).show();
        showKeyboard(editText);
    }


    private void handleImage(File fileImage){
        Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
        Tiny.getInstance().source(fileImage).asFile().withOptions(options).compress(new FileCallback() {
            @Override
            public void callback(boolean isSuccess, String outfile, Throwable t) {
                if (isSuccess) {
                    SPUtils.getInstance().put(ansStr+"_LXPIC",outfile);
                    dismissProgressDialog();
                }else{
                    dismissProgressDialog();
                    Toast.makeText(mContext,getString(R.string.put_pic_faile),Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}
